import { SaaSCommodityPageParams, SaaSCommodityListItem, SaaSCommodityForm, PhotoParam } from './model/commodityModel';
import { commodityHttp } from '/@/utils/http/axios';

enum Api {
  SaaSCommodityList = '/commodity/commoditiesByPage',
  SaaSComCreateOrUpdate = '/commodity/createOrUpdate',
  SaaSComDelete = '/commodity/delete/',
  SaaSAllCom = '/commodity/commodities',
  PHOTO_LIST = '/commodityPhoto/getPhotoList',
  UPLOAD_PHOTO = '/basic-api/saaslanding-product/commodityPhoto/uploadPhoto',
  DELETE_PHOTO = '/commodityPhoto/delete',
}

// SaaS Landing 分页获取商品列表
export const getSaaSCommodityList = (params: SaaSCommodityPageParams) => {
  params.model = {
    id: params.id || '',
    commodityName: params.commodityName || '',
  };
  return commodityHttp.post<SaaSCommodityListItem[]>({
    url: Api.SaaSCommodityList,
    params,
  });
};

export const createorUpdateSaaSCommodity = (params: SaaSCommodityForm) => {
  return commodityHttp.post<string>({ url: Api.SaaSComCreateOrUpdate, params });
};

export const deleteSaaSCommodity = (commodityId: string) => {
  return commodityHttp.delete<string>({ url: Api.SaaSComDelete + commodityId });
};

export const getAllSaaSCommodity = () => {
  return commodityHttp.get<SaaSCommodityListItem>({ url: Api.SaaSAllCom });
};

export const base64ImgtoFile = (dataurl, filename = 'file') => {
  const arr = dataurl.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const suffix = mime.split('/')[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], `${filename}.${suffix}`, {
    type: mime,
  });
};

export const getPhotoList = async (params: PhotoParam) => {
  const res = await commodityHttp.get({
    url: Api.PHOTO_LIST,
    params,
  });
  const result = [];
  let id = 0;
  res.photoList.forEach((item) => {
    item = 'data:image/png;base64, ' + item;
    item = base64ImgtoFile(item);
    item = {
      uid: id.toString(),
      name: res.nameList[id],
      status: 'done',
      url: URL.createObjectURL(item),
    };
    result.push(item);
    id++;
  });
  return result;
};

export const deletePhoto = (params: PhotoParam & { name: string }) => {
  return commodityHttp.get({ url: Api.DELETE_PHOTO, params });
};

export const uploadPhoto = (productId: string, file: File) => {
  return commodityHttp.uploadFile({ url: Api.UPLOAD_PHOTO }, { file, data: { productId, name: file.name } });
};
